package graph;

import java.util.Arrays;

/**
 * @ClassName GraphByMatrix
 * @Description 使用邻接矩阵来存储图
 * @Author ZJX
 * @Date 2024/9/8 19:01
 * @Version 1.0
 */
public class GraphByMatrix {
    private char[] arrayV;    // 顶点数组
    private int[][] matrix;   // 邻接矩阵 (二维数组)
    private boolean isDirect; // 是否为有向图

    public GraphByMatrix(int size,boolean isDirect) {
        this.arrayV = new char[size];
        matrix = new int[size][size];

        for (int i = 0; i < size; i++) {
            Arrays.fill(matrix[i],Constants.MAX);
        }

        this.isDirect = isDirect;
    }

//    初始化顶点数组
    public void initArrayV(char[] array){
        for (int i = 0; i < array.length; i++) {
            arrayV[i] = array[i];
        }
    }

//     在两个顶点之间添加一条边 并 添加边的权重
public void addEdge(char srcV, char destV, int weight) {
    int srcIndex = getIndexOfV(srcV);
    int destIndex = getIndexOfV(destV);

    if (srcIndex == -1 || destIndex == -1) {
        throw new IllegalArgumentException("顶点不存在");
    }
    matrix[srcIndex][destIndex] = weight;

    if (!isDirect) {
        matrix[destIndex][srcIndex] = weight;
    }
}


    private int getIndexOfV(char v) {
        for (int i = 0; i < arrayV.length; i++) {
            if(arrayV[i] == v) {
                return i;
            }
        }
        return -1;
    }

    public int getDevOfV(char v) {
        int index = getIndexOfV(v);
        if (index == -1) {
            throw new IllegalArgumentException("顶点不存在");
        }

        int degree = 0;

        if (isDirect) {
            // 处理有向图，返回出度和入度
            int outDegree = 0; // 出度
            int inDegree = 0;  // 入度

            // 计算出度（遍历行）
            for (int i = 0; i < matrix.length; i++) {
                if (matrix[index][i] != Constants.MAX) {
                    outDegree++;
                }
            }

            // 计算入度（遍历列）
            for (int i = 0; i < matrix.length; i++) {
                if (matrix[i][index] != Constants.MAX) {
                    inDegree++;
                }
            }

            degree = outDegree + inDegree;

        } else {
            // 处理无向图，顶点的度数即为它所在行的非无边标记的元素个数
            for (int i = 0; i < matrix.length; i++) {
                if (matrix[index][i] != Constants.MAX) {
                    degree++;
                }
            }
        }

        return degree;
    }

}
